﻿using SqlSugar;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using XMFramework.Models;
using XMFramework.MysqlService;

namespace XMFramework.Forms.Pages.Orders
{
    public partial class FOrder : UIPage
    {
        private SqlSugarScope db = SqlSugarHelper.Db;
        List<OrderModel> orderlist = new List<OrderModel>();
        public FOrder()
        {
            //初始化一次
            InitializeComponent();
            uiDatePicker1.Text = DateTime.Now.ToString("yyyy-MM-dd");
        }

        private void FOrder_Initialize(object sender, EventArgs e)
        {
            //每次打开页面初始化
            uiDatePicker2.Text = DateTime.Now.ToString("yyyy-MM-dd");

            if (!backgroundWorker1.IsBusy)
                backgroundWorker1.RunWorkerAsync();
        }
        
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                db.BeginTran();
                orderlist = db.Queryable<OrderModel>().Where(it => it.state == "新增").OrderBy(it => it.id, OrderByType.Desc).ToList();
                db.CommitTran();
            }
            catch (Exception ex)
            {
                db.RollbackTran();//数据回滚
                UIMessageTip.ShowError("插入失败 - 数据回滚!\n" + ex);
            }
            
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            uiDataGridView1.DataSource = orderlist;
            uiSymbolButton2.Enabled = false;
            uiSymbolButton5.Enabled = false;
        }

        private void uiDataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1)
            {
                uiTextBox8.Text = uiDataGridView1.Rows[e.RowIndex].Cells["id"].Value.ToString();//id
                uiTextBox1.Text = uiDataGridView1.Rows[e.RowIndex].Cells["contractCode"].Value.ToString();//合同编号
                uiTextBox2.Text = uiDataGridView1.Rows[e.RowIndex].Cells["materialCode"].Value.ToString();//物料编码
                uiTextBox3.Text = uiDataGridView1.Rows[e.RowIndex].Cells["productName"].Value.ToString();//产品名称
                uiTextBox9.Text = uiDataGridView1.Rows[e.RowIndex].Cells["remainder"].Value.ToString();//订单剩余数量
                uiTextBox4.Text = uiDataGridView1.Rows[e.RowIndex].Cells["orderNumber"].Value.ToString();//订单总数量
                uiDatePicker1.Value = Convert.ToDateTime(uiDataGridView1.Rows[e.RowIndex].Cells["deliveryDate"].Value);//交货期
                uiTextBox6.Text = uiDataGridView1.Rows[e.RowIndex].Cells["notes"].Value.ToString();//备注

                uiSymbolButton2.Enabled = true;
                uiSymbolButton5.Enabled = true;
                UIMessageTip.ShowOk("调用 - 状态");
            }
        }

        private void uiSymbolButton1_Click(object sender, EventArgs e)
        {
            //新增按钮
            OrderModel dataList = new OrderModel()
            {
                contractCode = uiTextBox1.Text,
                materialCode = uiTextBox2.Text,
                productName = uiTextBox3.Text,
                remainder = Convert.ToInt32(uiTextBox4.Text),
                orderNumber = Convert.ToInt32(uiTextBox4.Text),
                deliveryDate = Convert.ToDateTime(uiDatePicker1.Text),
                state = "新增",
                creationDate = Convert.ToDateTime(uiDatePicker2.Text),
                notes = uiTextBox6.Text
            };

            try
            {
                db.BeginTran();

                //int count = db.Insertable(dataList).ExecuteCommand();//插入数据
                var x = db.Storageable(dataList)
                    .SplitInsert(it => it.NotAny())
                    .WhereColumns(it => new { it.contractCode, it.materialCode })
                    .ToStorage();
                x.AsInsertable.ExecuteCommand();//不存在插入
                //x.AsUpdateable.IgnoreColumns(z => z.id).ExecuteCommand();//存在更新

                db.CommitTran();
                if (x.InsertList.Count > 0)
                    UIMessageTip.ShowOk("新增订单 - 成功");
                else
                    UIMessageTip.ShowWarning("已有订单 - 警告");
            }
            catch (Exception ex)
            {
                db.RollbackTran();//数据回滚
                UIMessageTip.ShowError("插入失败 - 数据回滚!\n" + ex);
            }



            if (!backgroundWorker1.IsBusy)
                backgroundWorker1.RunWorkerAsync();
        }
        private void uiSymbolButton5_Click(object sender, EventArgs e)
        {
            //更新按钮
            try
            {
                db.BeginTran();

                bool datafalg = db.Queryable<ProductionOrderModel>()
                    .Any(it => it.orderCode == uiTextBox8.Text);

                if (datafalg == true)
                {
                    UIMessageTip.ShowWarning("订单已下达 - 无法更新");
                }
                else
                {
                    int count = db.Updateable<OrderModel>()
                    .SetColumns(it => new OrderModel()
                    {
                        contractCode = uiTextBox1.Text,
                        materialCode = uiTextBox2.Text,
                        productName = uiTextBox3.Text,
                        remainder = Convert.ToInt32(uiTextBox9.Text),
                        orderNumber = Convert.ToInt32(uiTextBox4.Text),
                        deliveryDate = Convert.ToDateTime(uiDatePicker1.Text),
                        creationDate = Convert.ToDateTime(uiDatePicker2.Text),
                        notes = uiTextBox6.Text
                    })
                    .Where(it => it.id == Convert.ToInt32(uiTextBox8.Text)).ExecuteCommand();

                    if (count > 0)
                        UIMessageTip.ShowOk("更新订单 - 成功");
                    else
                        UIMessageTip.ShowWarning("未查询到订单 - 警告");
                }
                db.CommitTran();
            }
            catch (Exception ex)
            {
                db.RollbackTran();//数据回滚
                UIMessageTip.ShowError("插入失败 - 数据回滚!\n" + ex);
            }

            if (!backgroundWorker1.IsBusy)
                backgroundWorker1.RunWorkerAsync();
        }

        private void uiSymbolButton2_Click(object sender, EventArgs e)
        {
            //删除按钮
            try
            {
                db.BeginTran();

                bool datafalg = db.Queryable<ProductionOrderModel>()
                    .Any(it => it.orderCode == uiTextBox8.Text);

                if (datafalg == true)
                {
                    UIMessageTip.ShowWarning("订单已下达 - 无法删除");
                }
                else
                {
                    int count = db.Deleteable<OrderModel>().Where(it => it.id == Convert.ToInt32(uiTextBox8.Text)).ExecuteCommand();
                    if (count > 0)
                        UIMessageTip.ShowOk("删除订单 - 成功");
                    else
                        UIMessageTip.ShowWarning("未查询到订单 - 警告");
                }

                db.CommitTran();

            }
            catch (Exception ex)
            {
                db.RollbackTran();//数据回滚
                UIMessageTip.ShowError("插入失败 - 数据回滚!\n" + ex);
            }

            if (!backgroundWorker1.IsBusy)
                backgroundWorker1.RunWorkerAsync();
        }

        private void uiSymbolButton3_Click(object sender, EventArgs e)
        {
            //搜索按钮
            try
            {
                db.BeginTran();

                uiDataGridView1.DataSource = db.Queryable<OrderModel>()
                    .Where(it => it.state == "新增" && it.contractCode.Contains(uiTextBox5.Text) && it.productName.Contains(uiTextBox11.Text) && it.productName.Contains(uiTextBox7.Text))
                    .OrderBy(it => it.id, OrderByType.Desc).ToList();

                db.CommitTran();
            }
            catch (Exception ex)
            {
                db.RollbackTran();//数据回滚
                UIMessageTip.ShowError("插入失败 - 数据回滚!\n" + ex);
            }

            uiSymbolButton2.Enabled = false;
            uiSymbolButton5.Enabled = false;

        }

        private void uiSymbolButton4_Click(object sender, EventArgs e)
        {
            //清除按钮
            uiTextBox5.Clear();//合同号
            uiTextBox7.Clear();//产品名称
            uiTextBox11.Clear();//交期

            if (!backgroundWorker1.IsBusy)
                backgroundWorker1.RunWorkerAsync();
        }
    }
}
